package dao;

import java.sql.ResultSet;
import java.util.ArrayList;

import modal.ProductModal;


public class ProductsDAO extends BaseDAO{
	
	public void addProduct(String name, String price, int ownerId, String description, String photoUrl) throws Exception {
       String query = "INSERT INTO `products`(`Name`, `DesiredPrice`, `UserID`, `Description`, `PhotoUrl`) VALUES ('" + name+ "','" + price+ "',"  + ownerId + ",'" + description + "','"+ photoUrl+ "')";
       execQuery(query);
    }
	
	public ProductModal getProductwithProductId(int productId) throws Exception {
		String query = "SELECT * FROM `products` WHERE ProductID = '"+ productId +"'";
		ResultSet rs =execQuery(query);
		ProductModal product=null;
		if(rs.next()){
			product = new ProductModal(rs.getInt("ProductID"),rs.getString("Name"),rs.getString("DesiredPrice"),rs.getInt("UserID"), rs.getString("Description"), rs.getString("PhotoUrl"), rs.getInt("Status"));
		} 
		return product; 	
	}
	
	public ArrayList<ProductModal> searchProductName(String word) throws Exception{
		String query = "SELECT * FROM `products` WHERE `Name` LIKE '%"+word +"%'"; 
		ResultSet rs= execQuery(query);
		ProductModal prod = new ProductModal();
		ArrayList <ProductModal> prods = new ArrayList<ProductModal>();
		while(rs.next()){
			prod = new ProductModal(rs.getInt("ProductID"), rs.getString("Name"), rs.getString("DesiredPrice"), rs.getInt("UserID"), rs.getString("Description"), rs.getString("PhotoUrl"), rs.getInt("Status"));
			prods.add(prod);
		}
		return prods; 
	}
	
	public ArrayList<ProductModal> searchProductDescription(String word) throws Exception{
		String query = "SELECT * FROM `products` WHERE `Description` LIKE '%"+word +"%'"; 
		ResultSet rs= execQuery(query);
		ProductModal prod = new ProductModal();
		ArrayList <ProductModal> prods = new ArrayList<ProductModal>();
		while(rs.next()){
			prod = new ProductModal(rs.getInt("ProductID"), rs.getString("Name"), rs.getString("DesiredPrice"), rs.getInt("UserID"), rs.getString("Description"), rs.getString("PhotoUrl"), rs.getInt("Status"));
			prods.add(prod);
		}
		return prods; 
	}
	
	public ArrayList<ProductModal> getProductwithOwnerId(int UserID) throws Exception {
		String query = "SELECT * FROM `products` WHERE UserID  = "+ UserID +"";
		ResultSet rs =execQuery(query);
		ArrayList <ProductModal> product=new ArrayList<ProductModal>();
		while(rs.next()){
		ProductModal pr=new ProductModal(rs.getInt("ProductID"),rs.getString("Name"),rs.getString("DesiredPrice"),rs.getInt("UserID"), rs.getString("Description"), rs.getString("PhotoUrl"), rs.getInt("Status"));
		product.add(pr);
		} 
		return product; 
		}

	public void setStatusSold(int productId) throws Exception { // 1 means sold
		String query = "UPDATE `products` SET `Status`="+ 1 + " WHERE ProductId = "+ productId;
		execQuery(query);
	}

}



	
